//index.js
//获取应用实例
const app = getApp()

var routes = require('./routes.js');  


Page({
  data: {
      name:"",
      tel: "",
      carcode: "",
      appId:'wx311dcb53333ad350',
      code: app.globalData.code,
      headUrl:'',
      openId:'',
      userInfoInWX:{},
      userInfoInXZS:{},
    
      cellHeight: '100px',
      pageItems: [],
      isLogined:false
  },

  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '汽修小助手车主版',
      success: function (res) {
      }
    })
    app.isLogined = false
    this.startGetUserInfo();
    this.resetItems();
  },

  onReady: function () {
    // Do something when page ready.
  },
  onShow: function () {
    // Do something when page show.
  },
  onHide: function () {
    // Do something when page hide.
  },
  onUnload: function () {
    // Do something when page close.
  },

  onTabItemTap: function (page) {
    console.info('onTabItemTap' + page);
  },

 resetItems:function(){
     var that = this
     console.log(app);
     //调用应用实例的方法获取全局数据  
  

       var pageItems = [];
       var row = [];
       var len = routes.PageItems.length;//重组PageItems  
       len = Math.floor((len + 2) / 3) * 3;
       for (var i = 0; i < len; i++) {
         if ((i + 1) % 3 == 0) {
           row.push(routes.PageItems[i]);
           pageItems.push(row);
           row = [];
           continue;
         }
         else {
           row.push(routes.PageItems[i]);
         }
       }
       wx.getSystemInfo({
         success: function (res) {
           var windowWidth = res.windowWidth;
           that.setData({
             cellHeight: (windowWidth / 3) + 'px'
           })
         },
         complete: function () {
           that.setData({
             pageItems: pageItems
           })
         }
       })
     
 },
bindGetUserInfo: function (e) {
  console.log(e.detail.userInfo)
},
startGetUserInfo: function ( ) {
  if(this.data.tel.length != 11){
    wx.showToast({
      title: '手机号不足11位',
    });
    return
  }

  

  let that = this;
  wx.login({
    success: res => {
  var code = res.code;
  wx.getSetting({
    success: res => {
      console.log(res);
      if (res.authSetting['scope.userInfo']) {
        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
        wx.getUserInfo({
          success: res1 => {
            console.info(res1)

            let res2 = JSON.parse(res1.rawData);
            that.setData({
              userInfoInWX: res2,
              name: res2.nickName,
              headUrl: res2.avatarUrl
            });
            app.userInfoInWX = res2;

            wx.request({
              url: app.globalData.SERVER+'noticeboard/weixinJM', //仅为示例，并非真实的接口地址
              data: {
                'iv': res1.iv,
                'encryptedData': res1.encryptedData,
                'code': code,
              },
              header: {
                'content-type': 'application/json' // 默认值
              },
              success: function (res3) {
                console.log(res3.data)
                that.setData({
                  openId: res3.data.openId
                });

                app.globalData.openId = res3.data.openId;

                that.getUserInfoFromXZSServer(that, that.data.tel)



              }
            })
          }
        })
      }else{
        that.startGetUserInfo()
      }
    }
  })
    }
  })



},
//根据号码从小助手后台获取个人详细信息
getUserInfoFromXZSServer:function(that,_tel){
  wx.request({
    url: app.globalData.SERVER+'contact/queryUserInfo4MiniPro', //仅为示例，并非真实的接口地址
    data: {
      'tel': _tel,
    },
    method:'POST',
    header: {
      'content-type': 'application/json' // 默认值
    },
    success: function (res1) {
      console.log('getUserInfoFromXZSServer');

      console.log('getUserInfoFromXZSServer success' + JSON.stringify(res1))

      if (res1.data.code == 1){
        that.setData({
          userInfoInXZS: res1.data.ret,
          isLogined: true
        });
        app.globalData.openId = that.data.openId;
        wx.showToast({
          title: '授权登录成功',
          icon: 'success',
        });
      }else{
        wx.showToast({
          title: '车辆还未注册',
          icon: 'loading',
        });
      }
      

     

      app.isLogined = true
      app.userInfoInXZS = res1.data.ret

      that.updateContactOpenId(that, that.data.tel,that.data.openId)

      that.getShopFromXZSServer(that, res1.data.ret.owner)
    },
    fail: function (fail){
      console.log('getUserInfoFromXZSServer fail' + JSON.stringify(res.data))
    }
  })
},

//获取服务门店的详情
getShopFromXZSServer: function (that, _tel) {
  wx.request({
    url: app.globalData.SERVER+'users/getShopInfo4MiniPro', //仅为示例，并非真实的接口地址
    data: {
      'tel': _tel,
    },
    method: 'POST',
    header: {
      'content-type': 'application/json' // 默认值
    },
    success: function (res1) {
      console.log('getUserInfoFromXZSServer');

      console.log('getUserInfoFromXZSServer success' + JSON.stringify(res1))

      that.setData({
        shopInfo: res1.data.ret
      });
      
      app.shopInfo = res1.data.ret;

      wx.setNavigationBarTitle({
        title: res1.data.ret.name,
        success: function (res) {
        }
      })

    },
    fail: function (fail) {
      console.log('getUserInfoFromXZSServer fail' + JSON.stringify(res.data))
    }
  })
},
  
  checkHistoryRepairs:()=>{

    if (app.isLogined == false) {
      wx.showToast({
        title: '请先授权登录',
      });
    }



    
    wx.navigateTo({
      url: './subPages/historyRepais?openId='+this.data.openId,
    })
  },

  startShare:function(){
    wx.showShareMenu({
      withShareTicket: true
    })
  },
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '邀请好友',
      path: '/pages/tab2/index?id=123',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  bindinput: function (event){
    console.log('bindinput'+event.detail.value);
    this.setData({ tel: event.detail.value})
    app.globalData.tel = this.data.tel
  },
  //主动更新客户微信id
  updateContactOpenId: function (that,tel,openId) {
    wx.request({
      url: app.globalData.SERVER + 'contact/updateOpenId', 
      data: {
        'tel': tel,
        'openId': openId
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res1) {
        console.log('updateContactOpenId success' + JSON.stringify(res1))
      },
      fail: function (fail) {
      }
    })
  },

})